<template>
  <el-scrollbar style="height: 100%">
    <CustomerForm ref="CustomerForm" :onlyReade="onlyReade">
      <template #title>
        <Title v-if="!onlyReade" title="客户信息" :iconShow="true">
          <template slot="icon">
            <i
              class="V7_iconfont V7_iconV7tubiao_kehu"
              style="color: #008bee; font-size: 14px; margin-right: 5px"
            ></i>
          </template>
        </Title>
      </template>
      <template #btn
        ><el-button
          type="primary"
          size="mini"
          @click="save"
          v-if="!onlyReade"
          style="float: right"
          >保存</el-button
        ></template
      >
    </CustomerForm>
  </el-scrollbar>
</template>

<script lang="ts">
/**
 * 客户详情客户信息录入组件
 */
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import Title from '../common/title.vue'
import CustomerForm from './customerForm.vue'
import { commonAction, checkHideTel, deepClone } from '@/utils/common'
import { CommonModule } from '@/store/modules/common/index'
@Component({
  name: 'CustomerEdit',
  components: {
    CustomerForm,
    Title
  }
})
export default class CustomerEdit extends Vue {
  [x: string]: any
  @Ref() private readonly CustomerForm
  @Prop() private id
  @Prop({ default: () => false }) private onlyReade
  @Prop({ default: false }) private wecaht

  get getCustomerAllLabels () {
    let labelList = this.$store.state.common.publicCache.customerAllLabels || []
    labelList = labelList.filter(v => v.enabled)
    return labelList.map(v => ({ value: v.name, key: v._id }))
  }

  get getUserList () {
    return this.$store.state.common.publicCache.userList.map(v => ({ value: `${v.agentName} 【${v.agentNumber}】`, key: v._id }))
  }

  get getRegionList () {
    return this.$store.state.common.publicCache.region.result || []
  }

  get getDetailConfig () {
    const detailConfs = (CommonModule as any).publicCache.customerDetailConfig || []
    detailConfs.forEach(item => {
      if (item.field === 'labels') { // 客户标签
        item.choices = this.getCustomerAllLabels || []
      } else if (['lastCallUser', 'lastChatUser', 'updateUser', 'createUser', 'firstOwner', 'owner'].includes(item.field)) { // 跟人有关的字段
        item.choices = this.getUserList || []
      } else if (item.field === 'region') { // 省市区
        item.options = {}
        item.options.children = this.getRegionList || []
      }
    })
    return detailConfs
  }

  private validateOther = (rule, arr, callback) => { // 手机号，QQ,邮箱等多个表单的必填校验
    let flag = false
    const newArr = arr || []
    newArr.forEach(item => {
      if (item.value) {
        flag = true
      }
    })
    if (!flag) {
      callback(new Error('必填'))
    } else {
      callback()
    }
  }

  public initData (detailData: any) {
    const rules = {}
    this.getDetailConfig.map(item => {
      if (item.required) {
        if (item.type === 'other') {
          rules[item.field] = [{
            required: true,
            validator: this.validateOther,
            trigger: 'blur'
          }]
        } else {
          rules[item.field] = [{
            required: true,
            trigger: 'blur',
            message: '必填'
          }]
        }
      }
    })
    this.CustomerForm.setData(this.getDetailConfig, this.onlyReade ? {} : rules, detailData)
  }

  private valideSame (arr: any) {
    arr.map((item, index) => {
      if (item.value === arr[index + 1] && arr[index + 1].value) {
        return this.$message.error('')
      }
    })
  }

  private isSame (arr: any) {
    let same = false
    same = arr.some((item, index) => item.value === (arr[index + 1] && arr[index + 1].value))
    return same
  }

  private getTextName (key: any) {
    switch (key) {
      case 'mobile':
        return '手机号'
      case 'email':
        return '邮箱'
      case 'qq':
        return 'qq'
      case 'wechat':
        return '微信'
    }
  }

  private handleHideTel (arr) { // 手机号隐藏，在保存时候要匹配下，
    arr.forEach(item => {
      if (item.value === checkHideTel(item.bakValue)) { // 如果当前的value跟bakValue处理之后的一样，说没做改动，请求后端存储，用bakValue
        item.value = item.bakValue
      }
      delete item.bakValue
    })
    return arr
  }

  // 保存
  private save () {
    const { status, newForm } = this.CustomerForm.checkForm()
    const cloneForm = deepClone(newForm)
    if (status) {
      const sameVal: any = []
      const text: any = []
      Object.keys(cloneForm).map(item => {
        if (['mobile', 'email', 'qq', 'wechat'].includes(item) && cloneForm[item] && cloneForm[item].length > 1) {
          cloneForm[item] = cloneForm[item].filter(v => v.value) // 去掉空值
          sameVal.push(this.isSame(cloneForm[item]))
          text.push(this.getTextName(item))
        } else if (['mobile', 'email', 'qq', 'wechat'].includes(item) && JSON.stringify(cloneForm[item]) === '[{}]') {
          cloneForm[item] = []
        }
        if (item === 'mobile') {
          cloneForm.mobile = this.handleHideTel(cloneForm.mobile || [])
        }
      })
      const tMessage = sameVal.findIndex(v => v)
      if (tMessage > -1) {
        return this.$message.error(`${text[tMessage]}重复`)
      }
      const params = { url: '/server-crm/action/customer/update', method: 'POST', data: { ...cloneForm, id: this.id } }
      commonAction(params).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
          this.newForm = {}
          this.$emit('updateLog')
          if (this.wecaht) {
            this.$emit('updateCusInfo', {
              id: this.id,
              name: cloneForm.name,
              labels: cloneForm.labels
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="stylus" scoped>
>>> .title
  margin-bottom 12px
</style>
